package edu.hubu.CollectionTraverse;

import java.util.*;

public class MapTraverse {
    public static void main(String[] args) {
        //TODO:1.创建Map对象
        Map<Integer, String> map = new HashMap<>();

        //TODO:2.添加数据
        map.put(1, "唐僧");
        map.put(2, "孙悟空");
        map.put(3, "猪八戒");
        map.put(4, "沙僧");
        map.put(5, "白龙马");

        //TODO:3.采用Iterator迭代器遍历
        System.out.println("采用Iterator迭代器循环遍历HashMap集合:");
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.print("(" + key + ", " + value + ") ");
        }
        System.out.println("\n");

        //TODO:4.不能采用传统for循环遍历

        //TODO:5.采用增强for循环遍历，两种方式
        //方式一：使用keySet()，根据键集合取值
        System.out.println("采用增强for循环的方式一遍历HashMap集合:");
        Set<Integer> keySet = map.keySet();
        for (Integer key : keySet) {
            String value = map.get(key);
            System.out.print("(" + key + ", " + value + ") ");
        }
        System.out.println("\n");

        //方式二：使用entrySet()，根据键值对对象集合遍历
        System.out.println("采用增强for循环的方式二遍历HashMap集合:");
        Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
        for (Map.Entry<Integer, String> entry : entrySet) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.print("(" + key + ", " + value + ") ");
        }
        System.out.println("\n");

    }
}
